import Request from 'utils/request';
import SystemUtil from 'utils/systemUtil';

import moment from 'moment';

let qiniuUploader;

if (process.env.isMiniprogram) {
  qiniuUploader = require("./qiniuUploader-wxapp-min.js");
}

export default class QiniuUpload {
  static options = null;

  static getToken() {
    const apiName = 'api/qiniu/getQiniuToken';

    return Request.post(apiName).then(res => {
      return res.data;
    });
  }

  static initUploader() {
    let options = this.options;
    if (options !== null) {
      return window.Promise.resolve({
        result: true,
        options
      });
    }

    return this.getToken().then(token => {
      options = {
        region: 'SCN',
        uptoken: token,
        domain: 'https://qiniu.manlitech.com/'
      };
      qiniuUploader.init(options);
      this.options = options;
      return options;
    });
  }

  static uploadImg(filePath, name = '') {
    return this.initUploader().then(() => {
      return new window.Promise((resolve, reject) => {
        let str = SystemUtil.getRandomStr(4);
        let key = `${name}${moment().format('YYYYMMDDHHmmssSSS')}${str}`;
        qiniuUploader.upload(filePath, res => {
          let imageURL = res.fileUrl;
          resolve(imageURL);
        }, error => {
          reject(error);
        }, {
          key: key
        });
      });
    });
  }

  static uploadVideo(filePath, name = '') {
    return this.initUploader().then(() => {
      return new window.Promise((resolve, reject) => {
        let str = SystemUtil.getRandomStr(4);
        let key = `${name}${moment().format('YYYYMMDDHHmmssSSS')}${str}`;
        qiniuUploader.upload(filePath, res => {
          let videoURL = res.fileUrl;
          resolve(videoURL);
        }, error => {
          reject(error);
        }, {
          key: key
        });
      });
    });
  }
}
